package com.lj.back.manage.scaffold.module.job.utils;

import com.lj.back.manage.scaffold.common.exception.MyException;
import com.lj.back.manage.scaffold.common.response.ResponseCodeConstant;
import com.lj.back.manage.scaffold.common.util.EnumUtil;
import com.lj.back.manage.scaffold.module.job.constant.JobConstant;
import com.lj.back.manage.scaffold.module.job.DTO.ScheduleJobDTO;
import com.lj.back.manage.scaffold.module.job.enums.ScheduleStatusEnum;
import lombok.extern.slf4j.Slf4j;
import org.quartz.*;

import java.util.Objects;

/**
 * 定时任务工具类
 * @author lv
 */
@Slf4j
public class ScheduleUtils {

    /**
     * 获取触发器key
     */
    public static TriggerKey getTriggerKey(Long jobId) {
        return TriggerKey.triggerKey(JobConstant.JOB_NAME_PREFIX + jobId);
    }

    /**
     * 获取jobKey
     */
    public static JobKey getJobKey(Long jobId) {
        return JobKey.jobKey(JobConstant.JOB_NAME_PREFIX + jobId);
    }


    /**
     * 获取表达式触发器
     */
    public static CronTrigger getCronTrigger(Scheduler scheduler, Long jobId) {
        CronTrigger trigger = null;
        try {
            trigger = (CronTrigger) scheduler.getTrigger(getTriggerKey(jobId));
        } catch (SchedulerException e) {
            log.error("获取定时任务CronTrigger出现异常",e);
        }
        return trigger;
    }

    /**
     * 创建定时任务
     */
    public static void createScheduleJob(Scheduler scheduler, ScheduleJobDTO scheduleJob) {
        try {
            long jobId = Long.valueOf(scheduleJob.getId());
            JobKey jobKey = getJobKey(jobId);
            JobDetail jobDetail = scheduler.getJobDetail(jobKey);
            if (jobDetail != null){
                updateScheduleJob(scheduler,scheduleJob);
                return;
            }

            //构建新的job
            jobDetail = JobBuilder.newJob(ScheduleJob.class).withIdentity(getJobKey(jobId)).build();

            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCron())
            		.withMisfireHandlingInstructionDoNothing();

            //按新的cronExpression表达式构建一个新的trigger
            CronTrigger trigger = TriggerBuilder.newTrigger().withIdentity(getTriggerKey(jobId)).withSchedule(scheduleBuilder).build();

            //放入参数，运行时的方法可以获取
            jobDetail.getJobDataMap().put(JobConstant.JOB_PARAM_KEY, scheduleJob);

            scheduler.scheduleJob(jobDetail, trigger);
            
            //暂停任务
            if(Objects.equals(scheduleJob.getStatus(), ScheduleStatusEnum.PAUSE.getCode())){
            	pauseJob(scheduler, jobId);
            }
        } catch (SchedulerException e) {
            log.error("创建定时任务失败",e);
        }
    }

    
    /**
     * 更新定时任务
     */
    public static void updateScheduleJob(Scheduler scheduler, ScheduleJobDTO scheduleJob) {
        try {
            long jobId = Long.valueOf(scheduleJob.getId());
            TriggerKey triggerKey = getTriggerKey(jobId);

            //表达式调度构建器
            CronScheduleBuilder scheduleBuilder = CronScheduleBuilder.cronSchedule(scheduleJob.getCron())
            		.withMisfireHandlingInstructionDoNothing();

            CronTrigger trigger = getCronTrigger(scheduler, jobId);
            
            //按新的cronExpression表达式重新构建trigger
            trigger = trigger.getTriggerBuilder().withIdentity(triggerKey).withSchedule(scheduleBuilder).build();
            
            //参数
            trigger.getJobDataMap().put(JobConstant.JOB_PARAM_KEY, scheduleJob);
            
            scheduler.rescheduleJob(triggerKey, trigger);
            
            //暂停任务
            if(Objects.equals(scheduleJob.getStatus(), ScheduleStatusEnum.PAUSE.getCode())){
            	pauseJob(scheduler, jobId);
            }
            
        } catch (SchedulerException e) {
            log.error("更新定时任务失败",e);
        }
    }

    /**
     * 立即执行任务
     */
    public static void run(Scheduler scheduler, ScheduleJobDTO scheduleJob) {
        try {
            long jobId = Long.valueOf(scheduleJob.getId());
        	//参数
        	JobDataMap dataMap = new JobDataMap();
        	dataMap.put(JobConstant.JOB_PARAM_KEY, scheduleJob);
            scheduler.triggerJob(getJobKey(jobId), dataMap);
        } catch (SchedulerException e) {
            log.error("立即执行定时任务失败",e);
        }
    }

    /**
     * 暂停任务
     */
    public static void pauseJob(Scheduler scheduler, Long jobId) {
        try {
            scheduler.pauseJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            log.error("暂停定时任务失败",e);
        }
    }

    /**
     * 恢复任务
     */
    public static void resumeJob(Scheduler scheduler, Long jobId) {
        try {
            scheduler.resumeJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            log.error("恢复定时任务失败",e);
        }
    }

    /**
     * 删除定时任务
     */
    public static void deleteScheduleJob(Scheduler scheduler, Long jobId) {
        try {
            scheduler.deleteJob(getJobKey(jobId));
        } catch (SchedulerException e) {
            log.error("删除定时任务失败",e);
        }
    }

    /**
     * 操作定时任务
     * @param scheduler
     * @param jobId 定时任务ID
     * @param status 操作状态
     */
    public static void operateScheduleJob(Scheduler scheduler,long jobId, String status){
        boolean contains = EnumUtil.isValid(ScheduleStatusEnum.class,status);
        if (!contains){
            throw new MyException(ResponseCodeConstant.PARAM_ERROR, "定时任务状态无效");
        }
        if (Objects.equals(status, ScheduleStatusEnum.NORMAL.getCode())){
            ScheduleUtils.resumeJob(scheduler,jobId);
        }
        if (Objects.equals(status, ScheduleStatusEnum.PAUSE.getCode())){
            ScheduleUtils.pauseJob(scheduler,jobId);
        }
    }
}
